<?php
/**
 * Created by PhpStorm.
 * User: ycbwl
 * Date: 2018/10/23
 * Time: 12:09 AM
 */
namespace  app\api\model;

class Product extends Base {

    protected $table = 'product';

    protected $hidden = [
        'delete_time',
        'main_img_id',
        'from',
        'category_id',
        'create_time',
        'update_time'
    ];

    public function imgs(){
        return $this->hasMany('ProductImage','product_id','id');
    }

    public function properties(){
        return $this->hasMany('ProductProperty','product_id','id');
    }


    public function getUrlAttr($value,$data){
        if($data['from'] == 1){
            return config("setting.img_prefix").$value;
        }else{
            return $value;
        }
    }

    public function getMainImgUrlAttr($value,$data){
        if($data['from'] == 1){
            return config("setting.img_prefix").$value;
        }else{
            return $value;
        }
    }


    public static function getMostRecent($count = 10){
//        $products = self::order("create_time desc")->paginate($count,false,['page'=>1]);
        $products = self::order("create_time desc")->limit($count)->select();
        return $products;
    }

    public static function getProductsByCategoryID($categoryID){
        $products = self::where("category_id",$categoryID)->select();
        return $products;
    }

    public static function getProductDetail($id){
        $product = self::with(['imgs'=>function($query){
            $query->with(['imgUrl'])->order('order','asc');
        },'properties'])->find($id);
        return $product;
    }
}